package risoe.syslab.fhnew.hw.enocean.utils;

/*
 * Copyright (c) 2012-2014, Technical University of Denmark (DTU)
 * All rights reserved.
 * 
 * The Flexhouse 2.0 platform ("this software") is licensed under the
 * BSD 3-clause license.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *   - Neither the name of DTU nor the names of its contributors may be used to
 *     endorse or promote products derived from this software without specific
 *     prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE TECHNICAL UNIVERSITY OF DENMARK BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import jssc.SerialPort;
import jssc.SerialPortException;
import risoe.syslab.fhnew.hw.enocean.EnoceanMessage;
import risoe.syslab.fhnew.hw.enocean.EnoceanTRTRPSMessage;

/**
 * This Java application can be used to program Enocean actuators.
 * Supply the id and channel to program when executing this class.
 */
public class Programmer {

	private int address, channel;
	private SerialPort mSerialPort;

	public Programmer(String[] args) throws SerialPortException {
		if ( args.length < 2 ) {
			System.out.println("Usage: java " + Programmer.class.getName() + " ID  CHANNEL (PORT)" );
			System.exit(1);
		}
		String arg = args[0];
		if (arg.startsWith("0x") ) arg = arg.substring(2);
		address = (int) Long.parseLong( arg , 16 );
		channel = Integer.parseInt(args[1]);
		System.out.println( String.format( "Programming new address: %x, channel:", address, channel ) );

		String port = "/dev/ttyS0";
		if ( args.length > 2 ) {
			port = args[1];
		}

		BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) );
		System.out.println( "Please press the learn button, then press Enter" );
		System.out.println( "(LED should flash..)" );
		try {
			in.readLine();
		} catch (IOException e) {
			throw new IllegalArgumentException();
		}

		// Find the correct port and open a connection
		mSerialPort = new SerialPort(port);
		mSerialPort.openPort();

		// Initialize the serial port
		mSerialPort.setParams(9600, SerialPort.DATABITS_8,
				SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

		int[] actions = new int[]{ EnoceanTRTRPSMessage.DOWN, EnoceanTRTRPSMessage.RELEASE };
		for (int j = 0; j < actions.length; j++) {
			EnoceanMessage msg = new EnoceanTRTRPSMessage( address, channel, actions[j] );
			System.out.print(" Sending ");
			System.out.println( msg.getDataPacketAsString() );
			sendMessage(msg);
		}

		System.out.println( "Now press the CLR/RESET button, then press Enter" );
		try {
			in.readLine();
		} catch (IOException e) {
			throw new IllegalArgumentException();
		}

		System.exit(0);
	}
	
	private void sendMessage(EnoceanMessage e){
		try {
			char[] dp=e.getDataPacket();
			for (int i=0;i<dp.length;i++) {
				mSerialPort.writeByte((byte)dp[i]);
			}
		}
		catch (SerialPortException ex) {
			System.out.println("Failed to send message to device: "+e.getStringAddress());
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			new Programmer(args);
		} catch (SerialPortException e) {
			e.printStackTrace();
		}
	}

}
